# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*-
# Copyright (C) 2010 Joris Roovers
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.

# last updated Oct 20, 2010
# This is a quick first implementation, needs some work... 

# TODO cleanup + comments
# TODO execute actual logic in seperate thread
# TODO songs that already have a rating should not get a new rating


import rb, rhythmdb
import pygtk
import gtk
import os.path
import libxml2

ui_str = """
<ui>
  <menubar name="MenuBar">
    <menu name="ToolsMenu" action="Tools">
      <placeholder name="ToolsOps_5">
        <menuitem name="MergeRhythmboxRatings" action="MergeRhythmboxRating"/>
      </placeholder>
    </menu>
  </menubar>
</ui>
"""

class MergerhythmboxratingsPlugin (rb.Plugin):
    def __init__(self):
        rb.Plugin.__init__(self)
    def activate(self, shell):
        self.shell = shell
        ui_manager = shell.get_ui_manager()
        # couple action to menu
        action = gtk.Action ('MergeRhythmboxRating', 
                     _('Merge Rhythmbox Rating'), 
                     _('Merge Rhythmbox Rating 2'),
                     "")
        action.connect ('activate', self.merge_rhytyhmbox_ratings, shell)
        action_group = gtk.ActionGroup('MergeRhythmboxRatingGroup')
        action_group.add_action(action)
        ui_manager.insert_action_group(action_group,0)
        
        # add menu item
        ui_manager.add_ui_from_string(ui_str)
        manager.ensure_update()
        
    def merge_rhytyhmbox_ratings(self, action, shell):
        win = LocationDialog(self, self.shell)
        win.window.show_all()
        
    def deactivate(self, shell):
        del self.shell
        del self.string


class LocationDialog:
    
    def gtk_main_quit( self, window ):
        gtk.main_quit()
 
    def CancelButton_clicked_cb ( self, button ):
        self.window.hide()
    
    def OkButton_clicked_cb( self, button ):
        # read existing rhythmdb file and put the files with a rating in a dictionary
        doc = libxml2.parseFile(self.DBFileField.get_text())
        ratedFiles = {}
        for entry in doc.xpathEval('//rhythmdb/entry[rating]'):
            filename =  os.path.basename(entry.xpathEval("location")[0].content)
            rating = entry.xpathEval("rating")[0].content
            ratedFiles[str(filename)] = rating
        
        # iterate over library and match files 
        db = self.shell.get_property("db")
        src = self.shell.props.library_source
        treerow = src.props.base_query_model
        for treerow in src.props.base_query_model:
            entry, path = list(treerow)
            filename = os.path.basename(db.entry_get(entry, rhythmdb.PROP_LOCATION))
            if str(filename) in ratedFiles:
                db.set(entry, rhythmdb.PROP_RATING, float(ratedFiles[str(filename)]))
        
        self.statusLabel.set_text("DONE")
   
 
    def __init__( self, plugin, shelly ):
        builder = gtk.Builder()
        builder.add_from_file(plugin.find_file("ui.glade"))
        self.shell = shelly
        self.window = builder.get_object("window")
        self.statusLabel = builder.get_object("StatusLabel")
        self.DBFileField = builder.get_object("DBFileField")
        builder.connect_signals( self )
